<template>
  <div class="student-page">
    <div class="section-header">
          <p class="section-title">
            详细分析
          </p>
    </div>
    <!-- 筛选条件 -->
    <div class="top-controls">
      <div class="controls-left">
        <input v-model="search" class="select" style="width:250px" placeholder="请输入姓名/学号搜索" />
      </div>
      <div class="controls-right">
        <select v-model="selectedGroup" class="select">
          <option value="-1">全部分班</option>
          <option value="0">未分班</option>
          <!-- 动态生成分班 -->
          <option v-for="division in divisions" :key="division.division_id" :value="division.division_id">
            {{ division.division_name }}
          </option>
        </select>
         <button @click="openNewGroupDialog" class="button primary" style="background-color:#409EFF;margin-left:20px">新建分班</button>
      </div>
    </div>

    <!-- 学生列表 -->
    <div style="background-color:#F5F7FA;height:600px">
      <table class="student-table" v-if="students.length > 0">
        <thead style="background-color:#F5F5F5">
          <tr>
            <th>序号</th>
            <th>姓名</th>
            <th>学号</th>
            <th>分班</th>
            <th>手机号</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(student, index) in students" :key="student.stu_semester_id">
            <td>{{ index + 1 }}</td>
            <td>{{ student.username }}</td>
            <td>{{ student.stu_number }}</td>
            <td>{{ student.division_name }}</td>
            <td>{{ student.phone_num }}</td>
            <td>
              <span @click="openChangeGroupDialog(student)" class="change">调班</span> |
              <span @click="confirmExitClass(student)" class="out">移出课堂</span>
            </td>
          </tr>
        </tbody>
      </table>
      
      <!-- 显示无结果时的提示 -->
      <div v-else class="no-results">
        <img src="@/assets/picture/nostart.png" alt="无结果" class="empty-image" />
        <p class="empty-text">该分班还没有学生</p>
      </div>
    </div>
    <!-- 分页 -->
      <PagiNation 
      :currentPage="currentPage"
      :totalPages="totalPages"
      @page-change="fetchStudents($event)"
    />

    <!-- 新建分班对话框 -->
    <div v-if="dialogVisible" class="dialog-overlay" @click="closeDialog">
      <div class="dialog" @click.stop>
        <h2>新建分班</h2>
        <div>
          <label for="newGroupName">分班名称</label>
          <input v-model="newGroup.division_name" id="newGroupName" class="select" />
        </div>
        <div class="dialog-footer">
          <button @click="dialogVisible = false" class="button">取消</button>
          <button @click="createNewGroup" class="button primary">创建分班</button>
        </div>
      </div>
    </div>

    <!-- 调班对话框 -->
    <div v-if="changeGroupDialogVisible" class="dialog-overlay" @click="closeChangeGroupDialog">
      <div class="dialog" @click.stop>
        <h2>选择调班</h2>
        <div>
          <label for="changeGroupSelect">选择新分班</label>
          <select v-model="changeGroupData.division_id" id="changeGroupSelect" class="select">
            <option v-for="division in divisions" :key="division.division_id" :value="division.division_id">
              {{ division.division_name }}
            </option>
          </select>
        </div>
        <div class="dialog-footer">
          <button @click="changeGroupDialogVisible = false" class="button">取消</button>
          <button @click="changeGroup" class="button primary">确认调班</button>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { fetchDivisionList, fetchStudentList, createNewGroupAPI, changeStudentGroup, exitClassAPI } from '@/services/api';
import { watch } from 'vue';
import PagiNation from '@/components/PagiNation.vue';

export default {
    components: {
    PagiNation
  },
  setup() {
    // 状态定义
    const selectedGroup = ref('-1'); // 默认显示全部分班
    const search = ref('');
    const currentPage = ref(1);
    const pageSize = ref(5);
    const totalStudents = ref(0);
    const students = ref([]);
    const divisions = ref([]);
    const dialogVisible = ref(false);
    const changeGroupDialogVisible = ref(false);
    const exitClassDialogVisible = ref(false);
    const semesterId = localStorage.getItem('selectedClassId');
    const newGroup = reactive({ sem_id: semesterId, division_name: '' });
    const changeGroupData = reactive({ division_id: '', stu_semester_id: '' });

    // 计算属性
    const totalPages = computed(() => {
      const pages = Math.ceil(totalStudents.value / pageSize.value);
      return pages > 0 ? pages : 1; // 确保最小显示1页
    });

    // 获取分班列表
    const fetchDivisions = async () => {
      try {
        const response = await fetchDivisionList(semesterId);
        if (response.data.status === 1) {
          divisions.value = response.data.data;
          // 如果没有选中的分班，默认选中第一个
        } else {
          console.error('获取分班数据失败:', response.data.msg);
        }
      } catch (error) {
        console.error('获取分班数据失败:', error);
      }
    };

    // 获取学生列表
    const fetchStudents = async (page = 1) => {
      try {
        const semesterId = localStorage.getItem('selectedClassId');
        const response = await fetchStudentList(semesterId, selectedGroup.value, search.value, page, pageSize.value);
        if (response.data.status === 1) {
          students.value = response.data.data;
          totalStudents.value = response.data.total;
        } else {
          console.error('获取学生数据失败:', response.data.msg);
        }
      } catch (error) {
        console.error('获取学生数据失败:', error);
      }
    };

    // 创建新分班
    const createNewGroup = async () => {
      try {
        const response = await createNewGroupAPI(newGroup);
        ElMessage.success('新建分班成功');
        dialogVisible.value = false;
        
        // 先刷新分班列表
        await fetchDivisions();
       watch(selectedGroup, () => {
        currentPage.value = 1;
        fetchStudents();
      });
        // 自动选择新创建的分班
        selectedGroup.value = response.data.data.division_id;
        // 最后刷新学生列表
        // await fetchStudents();
      } catch (error) {
        ElMessage.error('新建分班失败');
      }
    };

    // 关闭对话框
    const closeDialog = () => {
      dialogVisible.value = false;
    };

    // 关闭调班对话框
    const closeChangeGroupDialog = () => {
      changeGroupDialogVisible.value = false;
    };

    // 关闭移出班级对话框
    const closeExitClassDialog = () => {
      exitClassDialogVisible.value = false;
    };

    // 调班
    const changeGroup = async () => {
      try {
        await changeStudentGroup(changeGroupData.stu_semester_id, changeGroupData.division_id);
        ElMessage.success('调班成功');
        changeGroupDialogVisible.value = false;

        // 保持当前筛选条件，刷新分班和学生列表
        await fetchDivisions(); // 刷新分班数据
        await fetchStudents(currentPage.value); // 刷新学生数据，保持当前页和筛选条件
      } catch (error) {
        ElMessage.error('调班失败');
      }
    };


    // 打开新建分班对话框
    const openNewGroupDialog = () => {
      dialogVisible.value = true;
    };

    // 打开调班对话框
    const openChangeGroupDialog = (student) => {
      changeGroupData.stu_semester_id = student.stu_semester_id;
      changeGroupDialogVisible.value = true;
    };

    // 确认移出班级
    const confirmExitClass = (student) => {
      ElMessageBox.confirm('确定要将此学生移出班级吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {  // 改为异步函数
        try {
          await exitClassAPI(student.stu_semester_id);  // 直接使用学生对象中的ID
          ElMessage.success('移出班级成功');
          await fetchStudents();  // 添加等待刷新
        } catch (error) {
          ElMessage.error('移出班级失败: ' + error.message);
        }
      }).catch(() => {});
    };

    // 生命周期钩子
    onMounted(() => {
      fetchDivisions();
      fetchStudents();
    });
    watch(selectedGroup, () => {
  currentPage.value = 1;  // 每次选择不同的分班时，从第一页开始
  fetchStudents();  // 重新加载学生数据
});

    // 统一返回
    return {
      selectedGroup,
      search,
      currentPage,
      pageSize,
      totalStudents,
      students,
      divisions,
      dialogVisible,
      changeGroupDialogVisible,
      exitClassDialogVisible,
      newGroup,
      changeGroupData,
      totalPages,
      fetchDivisions,
      fetchStudents,
      createNewGroup,
      changeGroup,
      openNewGroupDialog,
      openChangeGroupDialog,
      confirmExitClass,
      closeDialog,
      closeChangeGroupDialog,
      closeExitClassDialog
    };
  }
};
</script>

<style scoped>
.section-header {
  cursor: pointer;
  position: relative;
  padding: 10px;
  /* background: #f8f9fa; */
  border-radius: 4px;
  transition: background 0.3s;
}
.section-title {
  font-weight: bold;
  font-size: 18px;
  border-left: 4px solid #007bff;
  padding-left: 12px;
  margin-bottom: 15px;
}
.student-page {
  padding: 20px;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-color: #f5f7fa;
}

/* Container */
.container {
  background: #ffffff;
  min-height: 100vh;
  padding: 20px;
}

/* Filter Section */
.filter-section {
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  padding: 20px 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  color: #535353;
}

.filter-options {
  display: flex;
  gap: 15px;
  align-items: center;
  font-size: 14px;
}

.search-input {
  padding: 8px 12px;
  margin-right: 10px;
  width: 250px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #f5f7fa;
  font-size: 14px;
}

.search-button {
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
}

.search-button:hover {
  background-color: #66b1ff;
}

/* Top Controls */
.top-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* Select */
.select {
  padding: 8px 12px;
  font-size: 14px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background-color: #ffffff;
  color: #606266;
}

/* Table */
.student-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  background-color: #ffffff;
  border-radius: 10px;
}

.student-table th,
.student-table td {
  padding: 14px;
  text-align: center;
  font-size: 14px;
  color: gray;
}

.student-table th {
  /* background-color: #ececec; */
  color: #606266;
}

.student-table tr:hover {
  background-color: #f9f9f9;
}

/* No Results */
.no-results {
  text-align: center;
  margin-top: 50px;
}

.empty-image {
  width: 300px;
  margin-bottom: 20px;
  opacity: 0.8;
}

.empty-text {
  color: #888;
  font-size: 16px;
}

/* Dialog */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

/* Modal/Dialog */
.dialog {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  width: 400px;
  margin: auto;
}

.dialog h2 {
  font-size: 18px;
  color: #333;
  margin-bottom: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.dialog-footer button {
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.dialog-footer button:first-child {
  background-color: #f4f5f7;
  color: #606266;
}

.dialog-footer button:last-child {
  background-color: #409eff;
  color: white;
}

.dialog-footer button:hover {
  background-color: #66b1ff;
}

/* Buttons */
.button {
  padding: 8px 16px;
  font-size: 14px;
  border-radius: 4px;
  cursor: pointer;
  border: none;
  color: white;
}

.change:hover {
 text-decoration: underline;
}
.out:hover {
 text-decoration: underline;
}
.change {
  color: #f56c6c;
  cursor: pointer;
}

.out {
  color:#409eff;
  cursor: pointer;
}

/* Empty State */
.no-results {
  text-align: center;
  margin-top: 50px;
}

.empty-image {
  width: 200px;
  opacity: 0.8;
}

.empty-text {
  color: #888;
  font-size: 16px;
}

</style>
